import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/detail_widget/post_detail_cover_content.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/detail_widget/post_detail_operation_view.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/detail_widget/post_detail_pre_or_next_view.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/detail_widget/post_detail_word_content.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/detail_widget/post_resouce_info_widget.dart';
import 'package:xvideos/hj_page/community_business/post_detail_page/post_detail_controller.dart';
import 'package:xvideos/hj_page/home_business/widget/quick_search_view.dart';
import 'package:xvideos/hj_page/comment/cell/comment_item.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';
import 'package:provider/provider.dart';
import '../../comment/widget/comment_foot_view.dart';
import '../widget/post_user_info_view.dart';

List<VideoModel>? _filters(List<VideoModel>? videoModel) {
  List<VideoModel> list = [];
  for (VideoModel item in (videoModel ?? [])) {
    if (!item.isHotUp() && !item.isRandomAd() && !item.isAdsArr()) {
      list.add(item);
    }
  }
  return list;
}

class PostDetailPageArgument {
  final List<VideoModel>? videoModels;
  String? id;

  PostDetailPageArgument({List<VideoModel>? models, this.id}) : videoModels = _filters(models);
}

class PostDetailPage extends StatelessWidget {
  static const String routeName = '/home/post_detail';

  const PostDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: PostDetailController(),
      global: false,
      builder: (controller) {
        return Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(titleSpacing: 18.w, automaticallyImplyLeading: false, title: _postDetailTitle(controller)),
          body: () {
            if (controller.isLoading || controller.model == null) {
              return SizedBox(
                height: 300,
                child: LoadingCenterWidget(),
              );
            }
            return Stack(
              children: [
                Column(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 18.w),
                        child: pullYsRefresh(
                          enablePullDown: false,
                          onInit: (rctr) => controller.refreshController = rctr,
                          onLoading: (refreshController) => controller.fetchComments(controller.postDetailPageArgument?.id ?? ''),
                          child: CustomScrollView(
                            controller: controller.scrollCtr,
                            slivers: [
                              SliverToBoxAdapter(child: 14.h.sizeBoxH),

                              /// 用户信息
                              SliverToBoxAdapter(
                                child: PostUserInfoView(
                                  model: controller.model!,
                                  isDetailStyle: true,
                                ),
                              ),
                              // 标题
                              SliverToBoxAdapter(child: PostDetailWordContent(model: controller.model!)),
                              if (controller.model?.richText?.isNotEmpty != true)
                                SliverToBoxAdapter(child: PostDetailCoverContent(model: controller.model!)),
                              SliverToBoxAdapter(
                                child: GameDetaiWordContent(controller.model!),
                              ),
                              SliverToBoxAdapter(
                                child: PostDetailVideoContent(model: controller.model!),
                              ),

                              SliverToBoxAdapter(child: PostResourceInfoWidget(videoModel: controller.model!)),
                              SliverToBoxAdapter(child: 16.sizeBoxH),

                              SliverToBoxAdapter(
                                child: PostDetailOperationView(
                                  model: controller.model ?? VideoModel(),
                                ),
                              ),
                              // SliverToBoxAdapter(
                              //   child: PostPreOrNextWidget(
                              //     id: controller.postDetailPageArgument?.id ?? "",
                              //     videoArr: controller.postDetailPageArgument?.videoModels,
                              //     next: (id) {
                              //       controller.nextOrPrePost(id);
                              //     },
                              //     pre: (id) {
                              //       controller.nextOrPrePost(id);
                              //     },
                              //   ),
                              // ),
                              SliverToBoxAdapter(child: AdsGridViewWidget(7)),
                              SliverToBoxAdapter(
                                child: Container(
                                  padding: EdgeInsets.only(bottom: 14),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        '评论 (${controller.model?.commentCount ?? 0})',
                                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.white),
                                      ),
                                      if (controller.quickSearchList.isNotEmpty) ...[
                                        18.sizeBoxH,
                                        QuickSearchView(controller.quickSearchList)
                                      ]
                                    ],
                                  ),
                                ),
                              ),
                              if (controller.comments.isEmpty)
                                SliverToBoxAdapter(
                                  child: Container(
                                    height: 220,
                                    child: CErrorWidget(),
                                  ),
                                )
                              else
                                SliverList.builder(
                                  itemCount: controller.comments.length,
                                  itemBuilder: (_, index) => CommentItem(
                                    controller.comments[index],
                                    objId: controller.model?.id ?? '',
                                    replyHandler: (p0, {reply}) => controller.onCommentOrReplyAction(comment: p0, reply: reply),
                                  ),
                                )
                            ],
                          ),
                        ),
                      ),
                    ),
                    Obx(
                      () => CommentFootView(
                        videoModel: controller.model!,
                        isShowCollect:true,
                        begainCommentHandler: (value) => controller.onCommentOrReplyAction(isSend: value),
                        isSendStatus: controller.isSendingMsg.value,
                        textEditController: controller.commentController,
                        imagePath: controller.selectedImagePath.value,
                        imgCallback: (value) {
                          controller.selectedImagePath.value = value;
                        },
                      ),
                    )
                  ],
                ),
                // Positioned(
                //   bottom: 100,
                //   right: 20,
                //   child: InkWell(
                //     onTap: () {
                //       Get.back();
                //     },
                //     child: Container(
                //       alignment: Alignment.center,
                //       width: 40,
                //       height: 40,
                //       decoration: BoxDecoration(
                //         color: Color(0xff3476FF),
                //         borderRadius: BorderRadius.all(Radius.circular(40)),
                //       ),
                //       child: Text(
                //         '返回',
                //         style: TextStyle(
                //           color: Colors.white,
                //           fontSize: 14.sp,
                //         ),
                //       ),
                //     ),
                //   ),
                // )
              ],
            );
          }(),
        );
      },
    );
  }

  Widget _postDetailTitle(PostDetailController controller) {
    return ChangeNotifierProvider.value(
      value: controller.scrollCtr,
      child: Consumer<ScrollController>(builder: (_, ctr, __) {
        final isGame = controller.model?.newsType == 'ADULT_GAME';
        final title = {'SEED_LINK': '种子详情', 'ADULT_GAME': '游戏详情'};
        if (!ctr.hasClients || ctr.offset < 60 || isGame)
          return Stack(
            alignment: Alignment.centerLeft,
            children: [
              GestureDetector(
                onTap: () => Get.back(),
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 18,
                  color: Colors.white,
                ),
              ),
              Center(
                child: Text(title[controller.model?.newsType] ?? '帖子详情'),
              )
            ],
          );
        return Row(
          children: [
            GestureDetector(
              onTap: () => Get.back(),
              child: Icon(
                Icons.arrow_back_ios,
                size: 18,
                color: Colors.white,
              ),
            ),
            4.sizeBoxW,
            Expanded(child: () {
              return PostUserInfoView(
                model: controller.model!,
                isDetailStyle: true,
                avatarSize: 30,
              );
            }()),
          ],
        );
      }),
    );
  }
}
